
import React from 'react'

class DemoSettingEdit extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      data: {}
    }
  }

  componentWillReceiveProps(props) {
    this.setState({
      data: props.data
    })
  }

  onDataSubmit() {
    var name = $(this.refs.demoName).val(),
        phone = $(this.refs.demoPhone).val(),
        id = $(this.refs.demoId).val() || (new Date().getTime());
    var data = {
      id: id,
      name: name,
      phone: phone
    }
    if (this.props.isEdit) {
      this.props.onDataUpdate(data)
    }else {
      this.props.onDataCreate(data)
    }
  }

  onChange(event, key) {
    var value = $(event.target).val();
    var data = this.state.data;
    data[key] = value;
    this.setState({
      data: data
    })
  }

  render() {
    var self = this;
    return (
      <div className="modal fade" id="DemoSettingEdit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 className="modal-title" id="demo-modal-label">Modal title</h4>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label for="demo-name">Name</label>
                <input ref="demoName" type="text" className="form-control"
                        id="demo-name" placeholder="Name" value={self.state.data.name}
                        onChange={(event)=>this.onChange(event, "name")}/>
              </div>
              <div className="form-group">
                <label for="demo-phone">Phone</label>
                <input ref="demoPhone" type="text" className="form-control"
                        id="demo-phone" placeholder="Phone" value={self.state.data.phone}
                        onChange={(event)=>this.onChange(event, "phone")}/>
              </div>
              <input ref="demoId" value={self.props.data.id} hidden/>
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" className="btn btn-primary"
                      onClick={(event)=> this.onDataSubmit()}>Save changes</button>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default DemoSettingEdit
